import React, { Component } from "react";
import Header from "../../components/Header/Header";
import { reqcartdelete, reqcartedit, reqcartlist } from "../../http/api";
import { $pre } from "../../http/http";
import "./Shop.less";
import yImg from "../../assets/img/y.jpeg";
import nImg from "../../assets/img/n.jpeg";
import { Button, SwipeAction, Dialog, Toast } from "antd-mobile";
import { filterPrice } from "../../filters";

export class Shop extends Component {
  constructor() {
    super()
    this.state = {
      arr: [],
      allChecked: false
    }
    this.isrequest = true;
  }
  componentDidMount() {
    this.getlist()
  }
  async getlist() {
    let res = await reqcartlist({ uid: JSON.parse(sessionStorage.getItem("isLogin")).uid })
    if (res.data.code === 200) {

      let arr = res.data.list[1].content ? res.data.list[1].content : [];

      let oldarr = this.state.arr;
      arr.forEach(item => {
        let obj = oldarr.find(i => i.id === item.id)
        item.checked = obj ? obj.checked : false;
      })
      this.setState({
        arr,
        allChecked: arr.length > 0 ? arr.every(item => item.checked) : false
      },
        () => {
          this.isrequest = true;
        })
    }
  }
  async add(id) {
    let res = await reqcartedit({ id, type: 2 })
    if (res.data.code === 200) {
      Toast.show({
        content: res.data.msg
      })
      this.getlist()
    }
  }
  async sub(id, num) {
    if (num > 1 && this.isrequest) {
      this.isrequest = false
      let res = await reqcartedit({ id, type: 1 })
      if (res.data.code === 200) {
        Toast.show({
          content: res.data.msg
        })
        this.getlist()
      }
    }else{
      Toast.show({
        content:"宝贝不能再少了"
      })
    }
  }
  async del(id){
    let res = await reqcartdelete({id})
    if(res.data.code === 200){
      Toast.show({
        content:res.data.msg
      })
      this.getlist()
    }
  }
  changeAll(){
    this.setState({
      allChecked:!this.state.allChecked
    },()=>{
      this.state.arr.forEach(item=>{
        item.checked = this.state.allChecked
      })
      this.setState({
        arr:this.state.arr
      })
    })
  }
  changeOne(index){
    let {arr} = this.state
    arr[index].checked = !arr[index].checked
    this.setState({
      arr,
      allChecked:arr.every(item=>item.checked)
    })
  }
  render() {
    let { arr, allChecked } = this.state
    let allPrice = arr.reduce(
      (v, i) => (i.checked ? v + i.price * i.num : v),
      0
    );

    return (
      <div>
        <Header title="购物车" back></Header>
        {arr.map((item, index) => (
          <SwipeAction
            key={item.id}
            closeOnAction={false}
            closeOnTouchOutside={false}
            rightActions={[
              {
                key: "delete",
                text: "删除",
                color: "danger",
                onClick: async () => {
                  await Dialog.confirm({
                    content: "确定要删除吗？",
                    onConfirm: () => {
                      this.del(item.id);
                    },
                  });
                },
              },
            ]}
          >
            <div className="item">
              <img
                className="checkbox"
                src={item.checked ? yImg : nImg}
                alt=""
              />
              <img
                onClick={() => this.changeOne(index)}
                className="img"
                src={$pre + item.img}
                alt=""
              />
              <div className="right">
                <h3>{item.goodsname}</h3>
                <div>￥{filterPrice(item.price)}</div>
                <div>
                  <Button onClick={() => this.sub(item.id, item.num)}>-</Button>
                  {item.num}
                  <Button onClick={() => this.add(item.id)}>+</Button>
                </div>
              </div>
            </div>
          </SwipeAction>
        ))}

        {/* 全选总价 */}
        <div className="footer">
          <div className="allChecked" onClick={() => this.changeAll()}>
            <img className="checkbox" src={allChecked ? yImg : nImg} alt="" />
            全选
          </div>
          <div className="allPrice"><span>总计:</span>￥{filterPrice(allPrice)}</div>
          <Button shape='default' color="warning" onClick={()=>this.props.history.push("/order")}>结算</Button>
        </div>
      </div>
    )
  }
}

export default Shop